import { observable, action, flow, computed, configure } from "mobx";
import * as _ from 'lodash';

configure({ // 强制mobx只能通过 @action 修改状态
  enforceActions: 'observed'
});

const delay = ms => new Promise((resolve, reject) => setTimeout(resolve, ms));

function Apple(i) {
  this.id = i;
  this.name = `红苹果 - ${i}号`;
  this.weight = Math.floor(200 + (Math.random() - 0.5) * 10);
}

// 1、创建 store 对象 存储默认状态0
class CounterStore {
  appleIndex = 1; // 当前是第几号苹果
  @observable appleList = []; // 当前苹果列表
  @observable eatedApple = []; // 已经吃掉的
  @observable getting = false; // 是否正在摘苹果

  @action.bound eat(id) {
    const apple = _.remove(this.appleList, apple => {
      return apple.id === id;
    });
    this.eatedApple.push(...apple);
  }

  @computed get eatedWeight() {
    return this.eatedApple.reduce((total, apple) => total + apple.weight, 0);
  }

  @computed get nowWeight() {
    return this.appleList.reduce((total, apple) => total + apple.weight, 0);
  }

  getApple = flow(function* () {
    this.getting = true;
    yield delay(1000);
    const apple = new Apple(this.appleIndex++);
    this.appleList.push(apple);
    this.getting = false;
  }).bind(this);
}

const counter = new CounterStore();
export default counter;
// 2、将store对象放在一个全局的组件可以够得着的地方
// 3、让组件获取store对象中的状态，并将状态显示在组件中

